package com.example.learn_mybatis.controller;

import com.example.learn_mybatis.pojo.Result;
import com.example.learn_mybatis.pojo.Users;
import com.example.learn_mybatis.service.impl.UsersServiceImpl;
import com.example.learn_mybatis.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {
    @Autowired
    private UsersServiceImpl usersService;

    @PostMapping("/login")
    public Result login(@RequestBody Users user) {

        try{
            Map<String, Object> claims =  new HashMap<>();
            Users dbUser = usersService.getUser(user);
            if(dbUser == null) {
                return Result.error("用户密码错误");
            } else {
                claims.put("username", dbUser.getUsername());
                claims.put("id", dbUser.getId());
                String jwt = JwtUtil.generateToken(claims);
                return Result.success(jwt);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
